package org.liveboardgames.agricola.control.delegates
{
	import com.adobe.cairngorm.business.ServiceLocator;
	
	import mx.rpc.IResponder;
	
	import org.liveboardgames.agricola.model.AgricolaModelLocator;
	import org.liveboardgames.agricola.vo.common.IResourceContainer;
	import org.liveboardgames.agricola.vo.farm.Farm;
	import org.liveboardgames.agricola.vo.farm.FarmTile;
	import org.liveboardgames.common.dictionary.collections.HashCollection;
	import org.liveboardgames.common.dictionary.collections.IMap;

	public class AddResourceDelegate
	{
		private var _responder:IResponder;

		private var _service:Object;

		public function AddResourceDelegate(responder:IResponder)
		{
			this._service = ServiceLocator.getInstance().getRemoteObject("resourceService");
			this._responder = responder;
		}

		public function addResource(host:IResourceContainer, resources:IMap):void
		{
//            setTimeout(addResourceService, 0, host, resources);
			var type:String;
			var id:int;
			if (host is FarmTile)
			{
				type = "FarmTile";
				id = FarmTile(host).uniqueId;
			}
			else if (host is Farm)
			{
				type = "Farm";
				id = Farm(host).id;
			}
			else
			{
				throw new Error("Invalid host: " + host);
			}
			
			var call:Object = _service.addResource(AgricolaModelLocator.getInstance().game.id, id, type, resources.toObject());
			call.resultHandler = _responder.result;
			call.faultHandler = _responder.fault;
		}

		private function addResourceService(host:IResourceContainer, resources:HashCollection):void
		{
			// Check that the current player has played its peep
			host.addResources(resources);
		}
	}
}